package cn.neu.leon.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.neu.leon.util.Percentage;
import cn.neu.leon.util.Sentiment;
import cn.neu.leon.util.WeiboCrawler;

public class Pie extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw = response.getWriter();
		String userId = request.getParameter("userUrl");
		// String url = "http://weibo.cn/2765365605/profile?vt=4";
		Map<String,double[]> perMap = new LinkedHashMap<String,double[]>();
		WeiboCrawler wc;
		try {
			wc = new WeiboCrawler(userId);
			
			if(!wc.isIdExist())
			{
				pw.print("不存在该用户");
				pw.close();
			}
			else
			{
				ArrayList<String> userInfo = wc.getUserInfo();

				perMap = wc.getPerMap();
				double[] per = new double[7];
				Set<Map.Entry<String,double[]>> entrySet = perMap.entrySet();
				for (Map.Entry<String, double[]> entry:entrySet) {
					   
					   for(int i=0;i<7;i++)
					   {
						   per[i] +=entry.getValue()[i];
					   }
					  }
		        per = Percentage.format(per);
				
		        JSONArray series = new JSONArray();
				JSONObject data = new JSONObject();

				for (int i = 0; i < 7; i++) {
					JSONArray emotionArray = new JSONArray();
					emotionArray.add(Sentiment.sentimentCN[i]);
					emotionArray.add(per[i]);
					series.add(emotionArray);
				}

				data.put("userInfo", userInfo);
				data.put("series", series);

				String str = data.toString();
	
				System.out.println(str);
				pw.print(str);
				pw.close();
			}
			
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}
